﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace BattleThis.Core.Movement
{
	/// <summary>
	/// A list of paths.
	/// </summary>
	public class PathCollection : IEnumerable<Position>
	{

		#region Variablen
		private Dictionary<Position, Path> m_Dictionary = new Dictionary<Position, Path>();
		#endregion

		#region Properties

		#endregion

		#region Methoden

		/// <summary>
		/// Finds the path wich has the specified position.
		/// </summary>
		/// <param name="position">The position to find.</param>
		/// <returns></returns>
		public Path Find( Position position )
		{
			if( m_Dictionary.ContainsKey( position ) )
			{
				return m_Dictionary[ position ];
			}

			return Path.Close;
		}

		/// <summary>
		/// Determines whether [contains] [the specified position].
		/// </summary>
		/// <param name="position">The position.</param>
		/// <returns>
		///   <c>true</c> if [contains] [the specified position]; otherwise, <c>false</c>.
		/// </returns>
		public bool Contains( Position position )
		{
			return m_Dictionary.ContainsKey( position );
		}

		/// <summary>
		/// Adds the specified new path. If the added Path is Cheaper than an existing in the colleciton than 
		/// new new one overrides the old otherwise will be a ArgumentOutOfRangeException thrown.
		/// </summary>
		/// <param name="newPath">The new path.</param>
		public void Add( Path newPath )
		{
			if( newPath == null )throw new ArgumentNullException( "newPath" );

			if( m_Dictionary.ContainsKey( newPath.Target ) )
			{
				var existing = m_Dictionary[ newPath.Target ];

				if( newPath.IsCheaperAs( existing ) ) m_Dictionary[ newPath.Target ] = newPath;
				else throw new ArgumentOutOfRangeException( "path is not the cheaper as existing." );

				return;
			}

			m_Dictionary.Add( newPath.Target, newPath );
		}

		#region IEnumerable<Position> Member

		public IEnumerator<Position> GetEnumerator()
		{
			return m_Dictionary.Keys.GetEnumerator();
		}

		#endregion

		#region IEnumerable Member

		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
		{
			return m_Dictionary.Keys.GetEnumerator();
		}

		#endregion
		#endregion

	}
}